# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggplot2)
library(ggrepel)
library(dplyr)
library(tidyr)
library(tibble)
library(ropls)
library(pROC)
library(egg)
library(purrr)
library(stringr)
library(randomForest)
library(Boruta)
library(magrittr)
library(optparse)
library(caret)
library(PRROC)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

parent <- paste0("./")
createWhenNoExist(parent)

breaks <- seq(0, 1, by = 0.2)

data <- read.csv("Classification_Result.csv", header = T, stringsAsFactors = F)
uniqGroup <- unique(data$ClassNote)
group1Data <- data %>%
filter(ClassNote == uniqGroup[1])
group2Data <- data %>%
filter(ClassNote == uniqGroup[2])
rocRs <- roc.curve(group2Data$Value, group1Data$Value, curve = T)
pdf("ROC_Curve.pdf", width = 6, height = 6)
auc <- rocRs$auc
if (auc < 0.5) {
    rocRs <- roc.curve(group1Data$Value, group2Data$Value, curve = T)
}
plot(rocRs, main = "")
dev.off()

rocDf <- rocRs$curve %>%
    as.data.frame() %>%
    set_colnames(c("FPR", "Sensitivity", "Cutoff")) %>%
    select("Cutoff", everything())
write.csv(rocDf, "ROC_Curve_Data.csv", row.names = F)

plotData <- rocRs$curve %>%
as.data.frame()
plotData

colors <- hsv(h = seq(0, 1, length = 100) * 0.8, s = 1, v = 1)
yBreaks <- seq(0, 1, 0.2)

p <- ggplot(data = plotData, aes(x = V1, y = V2, color = V3)) +
    theme_bw(base_size = 8.8) +
    theme(plot.title = element_text(size = 14, hjust = 0.5, face = "bold"), panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(), axis.title.x = element_text(size = 12), axis.title.y = element_text(size = 12),
    axis.text.x = element_text(size = 12), axis.text.y = element_text(size = 12),
    plot.margin = unit(c(1, 0.5, 1, 0.5), "cm"), panel.border = element_rect(size = 0.75)
    ) +
    geom_line() +
    xlab("FPR") +
    ylab("Sensitivity") +
    ggtitle(str_c("AUC=", format(auc, digits = 3))) +
    labs(colour = "Cutoff") +
    scale_x_continuous("1 - Specificity", breaks = yBreaks) +
    scale_y_continuous("Sensitivity", breaks = seq(0, 1, 0.2)) +
    scale_colour_gradientn(colours = colors, breaks = yBreaks)

pdfFileName <- paste0("ROC_Curve.pdf")
ggsave(limitsize = FALSE,pdfFileName, p, width = 6, height = 6)










